/*
AlliedBridge Content Management System
Copyright (C) 2006 AlliedBridge

This program is free software; you can redistribute it and/or modify it under the
terms of the GNU General Public License as published by the Free Software Foundation;

This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied
warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.

You should have received a copy of the GNU General Public License along with this program; if not, write to the
Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
package org.volume4.alliedbridge.model.person;

import java.io.*;
import java.sql.*;
import java.util.Iterator;
import java.util.List;

import javax.servlet.*;
import javax.servlet.http.*;

import org.volume4.utils.ServletUtilities;
import org.apache.commons.fileupload.*;

public class UpdateMember extends HttpServlet {

	// Should the following three String declarations be private or final?
	// Should they be in an interface?
	public String DRIVER,URL,USER,PASS,fieldName,fieldData,fileName,fileFieldName;
	//public String folder = "c:\\tomcat\\webapps\\modelcup\\media\\profile\\";
    //public String tempFolder = "c:\\temp\\";
	public String folder = "/opt/tomcat5/webapps/mc/media/profile/";
    public String tempFolder = "/opt/tomcat5/webapps/mc/media/temp/";
	public String dest_folder,db_url,app_root,insert_table,messageSuccess,messageFailed,mem_number,
	first_name,last_name,area_represented,area_represented_abr,age,sex,height,waist,chest,
	eye_color,hair_color,shirt_dress_size,shoe_size,modeling_school,cup,img,img_alt;

	public void init() throws ServletException {
		ServletContext context = getServletContext();
		DRIVER = context.getInitParameter("driver");
		URL = context.getInitParameter("mc_dburl");
		USER = context.getInitParameter("mc_dbuser");
		PASS = context.getInitParameter("mc_dbpass");
	}

	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		response.setContentType("text/html");
		Connection con = null;
		// These need to be moved to a properties file.
		messageSuccess = "Member successfuly updated.";
		messageFailed = "Update member operation failed.";

		try {

	        DiskFileUpload upload = new DiskFileUpload();
	        upload.setSizeThreshold(4096);
	        upload.setRepositoryPath(tempFolder);
	        upload.setSizeMax(-1);

	        // Parse the request
	        List fileItems = upload.parseRequest(request);

	        // Process the uploaded fields
	        Iterator iter = fileItems.iterator();
	        while (iter.hasNext()) {
	        FileItem item = (FileItem) iter.next();

	        if (item.isFormField()) {

	            if(item.getFieldName().equals("mem_number")) {
	            	mem_number = ServletUtilities.filter(item.getString());
	            }
	            else if(item.getFieldName().equals("first_name")) {
	            	first_name = ServletUtilities.filter(item.getString());
	            }
	            else if(item.getFieldName().equals("last_name")) {
	            	last_name = ServletUtilities.filter(item.getString());
	            }
	            else if(item.getFieldName().equals("area_represented")) {
	            	area_represented = ServletUtilities.filter(item.getString());
                    area_represented_abr = ServletUtilities.provinceFilter(area_represented);
                }
	            else if(item.getFieldName().equals("age")) {
	            	age = ServletUtilities.filter(item.getString());
	            }
	            else if(item.getFieldName().equals("sex")) {
	            	sex = ServletUtilities.filter(item.getString());
	            }
	            else if(item.getFieldName().equals("height")) {
	            	height = ServletUtilities.filter(item.getString());
	            }
	            else if(item.getFieldName().equals("waist")) {
	            	waist = ServletUtilities.filter(item.getString());
	            }
	            else if(item.getFieldName().equals("chest")) {
	            	chest = ServletUtilities.filter(item.getString());
	            }
	            else if(item.getFieldName().equals("eye_color")) {
	            	eye_color = ServletUtilities.filter(item.getString());
	            }
	            else if(item.getFieldName().equals("hair_color")) {
	            	hair_color = ServletUtilities.filter(item.getString());
	            }
	            else if(item.getFieldName().equals("shirt_dress_size")) {
	            	shirt_dress_size = ServletUtilities.filter(item.getString());
	            }
	            else if(item.getFieldName().equals("shoe_size")) {
	            	shoe_size = ServletUtilities.filter(item.getString());
	            }
	            else if(item.getFieldName().equals("modeling_school")) {
	            	modeling_school = ServletUtilities.filter(item.getString());
	            }
	            else if(item.getFieldName().equals("cup")) {
	            	cup = ServletUtilities.filter(item.getString());
	            }
            } else {
	            if(item.getFieldName().equals("img")) {

	            	if(sex.equalsIgnoreCase("female")) {
	            		dest_folder = folder + "/girls/";
	            		db_url = "../media/profile/girls/";
	            	} else {
	            		dest_folder = folder + "/guys/";
	            		db_url = "../media/profile/guys/";
	            	}
	            int i = item.getName().lastIndexOf('\\');
	            img = ServletUtilities.filter(item.getName().substring(i+1));
	            if (!img.equalsIgnoreCase("")) {
	            File savedFile = new File(dest_folder, ServletUtilities.filter(item.getName().substring(i+1)) );
	            item.write(savedFile);

	            Class.forName(DRIVER);
				con = DriverManager.getConnection(URL,USER,PASS);

				String query = "UPDATE ab_members SET " +
						"mem_number= '" + mem_number + "', " +
						"first_name= '" + first_name + "', " +
						"last_name= '" + last_name + "', " +
						"area_represented= '" + area_represented + "', " +
                        "area_represented_abr= '" + area_represented_abr + "', " +
                        "age= '" + age + "', " +
						"sex= '" + sex + "', " +
						"height= '" + height + "', " +
						"waist= '" + waist + "', " +
						"chest= '" + chest + "', " +
						"eye_color= '" + eye_color + "', " +
						"hair_color= '" + hair_color + "', " +
						"shirt_dress_size= '" + shirt_dress_size + "', " +
						"shoe_size= '" + shoe_size + "', " +
						"modeling_school= '" + modeling_school + "', " +
						"cup= '" + cup + "', " +
						"img= '" + db_url + img + "', " +
						"img_alt= '" + first_name + " " + last_name + "'" +
						" WHERE mem_number= '" + mem_number + "'";

				PreparedStatement stmt = con.prepareStatement(query);

				int result = stmt.executeUpdate(query);
	            } else {
	            	Class.forName(DRIVER);
					con = DriverManager.getConnection(URL,USER,PASS);

					String query = "UPDATE ab_members SET " +
							"mem_number= '" + mem_number + "', " +
							"first_name= '" + first_name + "', " +
							"last_name= '" + last_name + "', " +
							"area_represented= '" + area_represented + "', " +
                            "area_represented_abr= '" + area_represented_abr + "', " +
                            "age= '" + age + "', " +
							"sex= '" + sex + "', " +
							"height= '" + height + "', " +
							"waist= '" + waist + "', " +
							"chest= '" + chest + "', " +
							"eye_color= '" + eye_color + "', " +
							"hair_color= '" + hair_color + "', " +
							"shirt_dress_size= '" + shirt_dress_size + "', " +
							"shoe_size= '" + shoe_size + "', " +
							"modeling_school= '" + modeling_school + "', " +
							"cup= '" + cup + "', " +
							"img_alt= '" + first_name + " " + last_name + "'" +
							" WHERE mem_number= '" + mem_number + "'";

					PreparedStatement stmt = con.prepareStatement(query);

					int result = stmt.executeUpdate(query);
	            }

				app_root = request.getContextPath();
				response.sendRedirect(app_root + "/application/application_messages/process_result.jsp?message=" + messageSuccess);

	            }
	        	}
	        }
		} catch (SQLException ex) {
			System.out.println("\nERROR:------ SQLException -----\n");
			while (ex != null) {
				System.out.println("Message: " + ex.getMessage());
				System.out.println("SQLState: " + ex.getSQLState());
				System.out.println("ErrorCode :" + ex.getErrorCode());
				ex = ex.getNextException();
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			try {
				if (con != null)
					con.close();
			} catch (SQLException ex) {
				System.out.println("\nERROR:------ SQLException -----\n");
				System.out.println("Message: " + ex.getMessage());
				System.out.println("SQLState: " + ex.getSQLState());
				System.out.println("ErrorCode :" + ex.getErrorCode());
			}
		}
	}

	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		doGet(request, response);
	}
}